package com.shanghaionstar.nav;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.annotation.OnClick;
import com.onstar.cn.framework.mvp.base.core.BaseFragment;
import com.onstar.cn.mag.dealer.PreferredDealerEntity;
import com.onstar.cn.map.common.PoiItemInfo;
import com.shanghaionstar.R;
import com.shanghaionstar.nav.adapter.AroundDealerListAdapter;
import com.shanghaionstar.nav.iview.INavAroundDealerView;
import com.onstar.cn.mag.dealer.AroundDealerRequestEntity;
import com.shanghaionstar.nav.presenter.NavAroundDealerPresenter;

import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.utils.JoinMeConstants;
import com.shanghaionstar.weight.TopLayout;

import java.util.List;

/**
 * 周边经销商列表页：
 * Created by Yonglang Hong on 2016/7/21.
 */
public class NavAroundDealerFragment extends BaseFragment implements INavAroundDealerView, View.OnClickListener, AdapterView.OnItemClickListener {

    @FindViewById(R.id.top_layout)
    private TopLayout top_layout;

    @FindViewById(R.id.prefer_dealer_layout)
    private LinearLayout prefer_dealer_layout;//首选经销商view
    @FindViewById(R.id.prefer_dealer_view)
    private RelativeLayout prefer_dealer_view;
    @FindViewById(R.id.text_prefer_delaer_title)
    private TextView text_prefer_delaer_title;
    @FindViewById(R.id.text_dealer_name)
    private TextView text_dealer_name;
    @FindViewById(R.id.text_dealer_address)
    private TextView text_dealer_address;
    @FindViewById(R.id.dealer_call_info)
    private TextView dealer_call_info;
    @FindViewById(R.id.dealer_distance)
    private TextView dealer_distance;

    /**
     * 数据容器
     **/
    @FindViewById(R.id.around_dealer_layout)
    private View around_dealer_layout;

    /**
     * 更多view
     **/
    @FindViewById(R.id.more_layout)
    private View more_layout;

    @FindViewById(R.id.tv_more)
    private View tv_more;

    @FindViewById(R.id.more_progress)
    private View more_progress;

    /**
     * 周边经销商列表
     **/
    @FindViewById(R.id.lsv_dealers)
    private ListView lsv_dealers;

    /**
     * 无数据
     **/
    @FindViewById(R.id.tv_no_datas)
    private View tv_no_datas;

    /**
     * 页面加载进度框
     **/
    @FindViewById(R.id.package_list_progress)
    private View package_list_progress;

    /**
     * 周边经销商列表数据适配
     **/
    private AroundDealerListAdapter dealerListAdapter;

    /**
     * 请求实体
     **/
    private AroundDealerRequestEntity dealerRequestEntity;

    /**
     * 周边经销商业务处理层
     **/
    private NavAroundDealerPresenter dealerPresenter;

    @Override
    public int getLayoutId() {
        return R.layout.nav_fragment_around_dealer;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        init();
    }

    /**
     * 初始化:
     */
    private void init() {
        prefer_dealer_layout.setVisibility(View.GONE);
        lsv_dealers.setOnItemClickListener(this);
        //默认从零开始，为了统一调用，在line：230都会：+1，故初始值改成：-1
        getDealerRequestEntity().setPageIndex(-1);
        //请求数据初始化
        initRequestEntity();
        //显示加载进度
        showProgressPage(true);
        //绑定数据适配器
        setAdapter();
        //异步加载数据
        loadDealerList();

        top_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(getArguments().getString(FinalConstants.FROM_PAGE)!=null && NavMapFragment.class.getSimpleName().equals(getArguments().getString(FinalConstants.FROM_PAGE))) {
                    baseActivity.finish();
                }else {
                    goBack();
                }
            }
        });
    }

    @OnClick({R.id.btn_back, R.id.tv_no_datas, R.id.more_layout})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_back:
                back();
                break;
            case R.id.tv_no_datas:
                reload();
                break;
            case R.id.more_layout:
                loadMore();
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        PreferredDealerEntity entity = (PreferredDealerEntity) getDealerListAdapter().getItem(position);
        PoiItemInfo poiItemInfo = new PoiItemInfo();
        poiItemInfo.setLatitude((entity.getLocationCoordinate().getLatitude()));
        poiItemInfo.setLongitude((entity.getLocationCoordinate().getLongitude()));
        poiItemInfo.setTelphone(entity.getTelephone());
        poiItemInfo.setTitle(entity.getDealerName());
        poiItemInfo.setAddress(entity.getAddress());
        poiItemInfo.setCityCode(entity.getCityCode());
        gotoPoiDetail(poiItemInfo, entity.getDistanceWithUnit());
    }

    private void gotoPoiDetail(PoiItemInfo poiItemInfo, String dealer_distance) {
        baseActivity.addFragment(baseActivity.getSupportFragmentManager(), NavPoiDetailFragment.newInstance(poiItemInfo), true);
        baseActivity.showFragment(baseActivity.getSupportFragmentManager(), NavPoiDetailFragment.class, NavAroundDealerFragment.class);
    }

    @Override
    public void back() {
//        super.back();
        baseActivity.removeCurrentAndShowPrevFragment(baseActivity.getSupportFragmentManager(), NavAroundDealerFragment.class);
    }

    /**
     * 初始化请求参数：
     * 主要设置经纬度。
     */
    private void initRequestEntity() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            PoiItemInfo itemInfo = (PoiItemInfo) bundle.getSerializable(Constants.POIITEMINFO);
            if (itemInfo != null) {
                getDealerRequestEntity().setLatitude(itemInfo.getLatitude());
                getDealerRequestEntity().setLongitude(itemInfo.getLongitude());
            }
        }
    }

    /**
     * 显示加载页
     *
     * @param isShow
     */
    private void showProgressPage(boolean isShow) {
        package_list_progress.setVisibility(isShow ? View.VISIBLE : View.GONE);
    }

    /**
     * 绑定数据适配器
     */
    private void setAdapter() {
        lsv_dealers.setAdapter(getDealerListAdapter());
    }

    public AroundDealerListAdapter getDealerListAdapter() {
        if (dealerListAdapter == null) {
            dealerListAdapter = new AroundDealerListAdapter(getContext());
        }
        return dealerListAdapter;
    }

    /**
     * 请求经销商列表数据
     */
    private void loadDealerList() {
        getDealerRequestEntity().setPageIndex(getDealerRequestEntity().getPageIndex() + 1);
        getDealerRequestEntity().setPageSize(getDealerListAdapter().getCount());
        getPresenter().getAroundDealerList(getDealerRequestEntity());
    }

    /**
     * 请求更多经销商列表数据
     */
    private void loadMore() {
        tv_more.setVisibility(View.GONE);
        more_progress.setVisibility(View.VISIBLE);
        loadDealerList();
    }

    public AroundDealerRequestEntity getDealerRequestEntity() {
        if (dealerRequestEntity == null) {
            dealerRequestEntity = new AroundDealerRequestEntity();
        }
        return dealerRequestEntity;

    }

    private NavAroundDealerPresenter getPresenter() {
        return dealerPresenter == null ? new NavAroundDealerPresenter(baseActivity.getScheduler(), this, getContext()) : dealerPresenter;
    }

    @Override
    public void showDealers(List<PreferredDealerEntity> dealerEntityList) {
        showProgressPage(false);
        tv_no_datas.setVisibility(View.GONE);
        around_dealer_layout.setVisibility(View.VISIBLE);
        showPreferDealer(dealerEntityList);
        getDealerListAdapter().add(dealerEntityList);
    }

    /**
     * 显示首选经销商
     *
     * @param dealerEntityList
     */
    private void showPreferDealer(List<PreferredDealerEntity> dealerEntityList) {
        if (prefer_dealer_layout.getVisibility() != View.VISIBLE) {
            String loginRole = ApplicationUtil.getInstance().getLoginRole();
            if (ApplicationUtil.getInstance().isLogin()
                    && !CommonUtil.isNull(loginRole)
                    && !loginRole.equalsIgnoreCase(JoinMeConstants.VISITOR)) {

                PreferredDealerEntity preferDealer = null;
                if (!CommonUtil.isNull(dealerEntityList) && dealerEntityList.size() > 0) {
                    preferDealer = dealerEntityList.get(0);
                    dealerEntityList.remove(0);
                }
                if (!CommonUtil.isNull(preferDealer)
                        && !CommonUtil.isNull(preferDealer.getDealerName())
                        && preferDealer.getIsPreferredDealer()) {
                    prefer_dealer_layout.setVisibility(View.VISIBLE);
                    text_dealer_name.setText(preferDealer.getDealerName());
                    text_dealer_address.setText(preferDealer.getAddress());
                    dealer_call_info.setText(preferDealer.getTelephone());
                    dealer_distance.setText(preferDealer.getDistanceWithUnit());
                }
            }
        }
    }

    @Override
    public void showMoreLayout(boolean isShow) {
        more_layout.setVisibility(isShow ? View.VISIBLE : View.GONE);
        tv_more.setVisibility(isShow ? View.VISIBLE : View.GONE);
        more_progress.setVisibility(!isShow ? View.VISIBLE : View.GONE);
    }

    @Override
    public void showEmpty() {
        getDealerRequestEntity().setPageIndex(getDealerRequestEntity().getPageIndex() - 1);
        showProgressPage(false);
        around_dealer_layout.setVisibility(View.GONE);
        tv_no_datas.setVisibility(View.VISIBLE);
        tv_no_datas.setEnabled(false);
        ((TextView) tv_no_datas).setText(getResources().getString(R.string.no_dealer_data));
    }

    @Override
    public void setLoading(boolean isLoading) {
    }

    @Override
    public void onResponseError(OnStarException e) {
        if (getDealerListAdapter().getCount() <= 0) {
            showEmpty();
            tv_no_datas.setEnabled(true);
            ((TextView) tv_no_datas).setText("获取失败，点击重新获取");
        }
    }

    private void reload() {
        showProgressPage(true);
        loadDealerList();
    }

    @Override
    public void onReponseSuccess(Object object) {
    }

    @Override
    public Activity onActivity() {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        release();
    }

    private void release() {
        if (dealerPresenter != null) {
            dealerPresenter.finish();
            dealerPresenter = null;
        }
    }

    public static NavAroundDealerFragment newInstance(PoiItemInfo poiItemInfo) {
        return newInstance(poiItemInfo,null);
    }

    public static NavAroundDealerFragment newInstance(PoiItemInfo poiItemInfo, String fromPage) {
        NavAroundDealerFragment navAroundDealerFragment = new NavAroundDealerFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("poiItemInfo", poiItemInfo);
        if(fromPage!=null) {
            bundle.putString(FinalConstants.FROM_PAGE, fromPage);
        }
        navAroundDealerFragment.setArguments(bundle);
        return navAroundDealerFragment;
    }

    public void onFragmentBackPress() {
        if(getArguments().getString(FinalConstants.FROM_PAGE)!=null && NavMapFragment.class.getSimpleName().equals(getArguments().getString(FinalConstants.FROM_PAGE))) {
            baseActivity.finish();
        }else {
            goBack();
        }
    }
}
